/*
 * @Author: yangzonglong
 * @Date: 2021-03-10 16:10:35
 * @version: v1.0.0
 * @Descripttion: Text 控制器
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-07-23 10:52:59
 * @Auditor:
 */
import React, { useState, } from 'react';
import { Input, Modal, Form } from 'antd';
import CodeMirror from '@uiw/react-codemirror';
import Icon from './../icon/Icon';
import { javascript } from '@codemirror/lang-javascript';
import useControlOptions from '../../hooks/useControlOptions';
import { TemplateProps } from './Template';

const screenIcon: React.CSSProperties = {
  position: 'absolute',
  right: 0,
  top: '20px'
}

const FormItem = Form.Item;
const extensions = [javascript({ jsx: true })];

const Controller = () => {
  const { options: { templateProps, formItemProps }, id, changeControlProps, changeFormItemProps } = useControlOptions<TemplateProps>('templateProps');

  const [visible, setVisible] = useState(false);
  const [codeMirrorValue, setCodeMirrorValue] = useState('');

  function show() {
    setVisible(true);
    setCodeMirrorValue(templateProps?.scriptText || '');
  }

  function onOk() {
    setVisible(false);
    changeControlProps('templateProps', {
      ...templateProps,
      scriptText: codeMirrorValue
    }, true);
    setCodeMirrorValue('');
  }

  return (
    <>
      <FormItem label="数据绑定ID" tooltip="数据存储的名称/英文/必填">
        <Input onChange={(e) => changeFormItemProps('name', e.target.value)} value={formItemProps?.name as string} />
      </FormItem>
      <FormItem label="标题" >
        <Input onChange={(e) => changeFormItemProps('label', e.target.value)} value={formItemProps?.label as string} />
      </FormItem>
      <div style={{ position: 'relative' }}>
        <FormItem label='模板内容'>
          <CodeMirror
            value={templateProps?.scriptText}
            onChange={(e: string) => {
              if (window._ACTIVE_ID_ !== id) return;
              changeControlProps('templateProps', {
                ...templateProps,
                scriptText: e
              }, true);

            }} />
        </FormItem>
        <Icon
          style={screenIcon}
          icon='&#xe67c;'
          onClick={show} />
      </div>
      <Modal
        visible={visible}
        title='模板'
        width={1000}
        onCancel={() => setVisible(false)}
        onOk={onOk}>
        <CodeMirror
          extensions={extensions}
          onChange={setCodeMirrorValue}
          value={codeMirrorValue} />
      </Modal>
    </>
  );
};

export default Controller;
